/*
 * Copyright 2011 Dominik Pretzsch <dominik.pretzsch at gmail.com>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package de.blacksheep.jmoteextract.extraction;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * <code>ExtractionQueue</code> provides a thread-safe QUEUE, which <br>
 * holds {@see ExtractionCallable}s. The QUEUE is <br>
 * managed by {@see ExtractionQueueManager}.
 * 
 * @author Dominik Pretzsch <dominik.pretzsch at gmail.com>
 */
public class ExtractionQueue {
    
    private static ExtractionQueue instance;
    private LinkedBlockingDeque<ExtractionCallable> QUEUE;
    
    private static final Logger LOGGER =  Logger.getLogger(ExtractionQueue.class.getName());

    private ExtractionQueue() {
        QUEUE = new LinkedBlockingDeque<ExtractionCallable>();
    }
    
    public static ExtractionQueue getInstance() {
        if (instance == null)
            instance = new ExtractionQueue();
        return instance;
    }
    
    public void enqueue(ExtractionCallable ec) {
        if (alreadyQueued(ec))
            return;
        
        LOGGER.log(Level.FINE, "Adding archive to queue...");        
        QUEUE.addLast(ec);
        synchronized (this) {
            LOGGER.log(Level.FINE, "Notify waiting threads...");
            notify();
        }
    }
    
    public ExtractionCallable dequeue() {                                    
        ExtractionCallable ec = null;
        try {
            ec = (ExtractionCallable) QUEUE.takeFirst();
        } catch (InterruptedException ex) {
            LOGGER.log(Level.SEVERE, null, ex);
        }               
        return ec;
    }
    
    public boolean isEmpty() {
        return QUEUE.isEmpty();
    }
    
    public boolean alreadyQueued(ExtractionCallable ec) {
        return QUEUE.contains(ec);
    }
}
